<template>
  <view class="container">
    <view v-if="userType == 1 || userType == 2">
      <view class="header-wrap">
        <view class="tab-box">
          <view class="tags">
            <view v-if="titleLists.length===2" v-for="item in titleLists" @click="clickItem(item)" class="tag-view"
              :class="{'active': item===currentTab}">
              {{item}}
            </view>
          </view>
          <view class="search-box" @click="showPopClick">
            <text style="width:130rpx;">更多查询</text>
            <image :src="filterIcon" style="width: 20px;height:20px" />
          </view>
        </view>
      </view>
      <view class="goods-list">
        <view v-if="currentTab==='销售'" class="item" @click.prevent="goToSaleDetail(item)"
          v-for="(item, index) in goodsData" style="margin-bottom: 10px">
          <sale-waybill :itemList="item" :confirmAudit="confirmAudit" :confirmCancel="confirmCancel"
            :orgNameShow="orgNameShow" @cancelWaybill="cancelWaybill" @confirmExamine="confirmExamine"></sale-waybill>
        </view>
        <view v-if="currentTab==='采购'" class="item" @click.prevent="goToDetail(item)" v-for="(item, index) in goodsData"
          style="margin-bottom: 10px">
          <goods-number :hasPermConfirm="hasPermConfirm" :hasPermCancel="hasPermCancel" :itemList="item"
            :orderSuspend="orderSuspend" @guaqiFun="showGuaqiDialog" @cancelFun="showCancelDialog"
            @confirmGoodFun="showGoodsDialog" @huifuFun="showHuifuDialog" @showButton="showButton"></goods-number>
        </view>
        <uni-load-more :status="pageParams.isMore" />
      </view>
    </view>
    <view v-else class="loading-search">
      <view class="header-wrap">
        <view class="tab-box">
          <view class="tags">
            <u-subsection :list="titleListsType" :current="currentTabs" inactiveColor="#409EFE" mode="subsection"
              @change="clickItemFun"></u-subsection>
          </view>
        </view>
      </view>
      <view class="search-boxs" v-if="currentTabs===0">
        <view class="items-content">
          <view class="items">
            <input class="short" maxlength="8" placeholder-style="color:#999999" v-model="paramunLoaded.carBrand"
              placeholder="请输入车牌号" />
          </view>
          <view class="items">
            <view class="select-wrap" :style="{
                color: !!paramunLoaded.proId ? '#333' : '#D9D9D9'
              }" @click="chooseProFun">
              <text class="select-label">{{ !!paramunLoaded.proId ? productText : '请选择煤种' }}</text>
              <uni-icons v-if="!!paramunLoaded.proId" class="select-icon-close" type="close" size="20"
                @click.native.stop="closeFun(1)" color="#D9D9D9"></uni-icons>
              <uni-icons class="select-icon" type="right" size="20" color="#D9D9D9"></uni-icons>
            </view>
          </view>
        </view>

        <view class="footer">
          <button plain type="primary" @click="confirmFilter()" class="font15">查询</button>
        </view>
      </view>
      <view class="search-boxs" v-else>
        <view class="items full">
          <input class="short" maxlength="8" placeholder-style="color:#999999" v-model="paramLoaded.carBrand"
            placeholder="请输入车牌号" />
        </view>
        <view class="items full items-content">
          <view class="uni-form-item">
            <w-picker :visible="isStart" class="disab-box" mode="date" startYear="1900" endYear="2124" :current="false"
              fields="second" @confirm="onConfirm($event,'startTime')" @cancel="onCancel" :disabled-after="false"
              ref="date1"></w-picker>
            <input v-model="paramLoaded.startTime" class="uni-input prd-mess" placeholder="请选择开始时间" disabled="true"
              placeholder-style="color: #999;" @click="showStartTime"></input>
            <uni-icons v-if="!!paramLoaded.startTime" class="select-icon-close" type="close" size="20"
              @click.native.stop="closeFun(2)" color="#D9D9D9"></uni-icons>
          </view>
        </view>
        <view class="items full items-content">
          <view class="uni-form-item">
            <w-picker :visible="isEnd" class="disab-box" mode="date" startYear="1900" endYear="2124" :current="false"
              fields="second" @confirm="onConfirm($event,'endTime')" @cancel="onCancel" :disabled-after="false"
              ref="date1"></w-picker>
            <input v-model="paramLoaded.endTime" class="uni-input prd-mess" placeholder="请选择结束时间" disabled="true"
              placeholder-style="color: #999;" @click="showEndTime"></input>
            <uni-icons v-if="!!paramLoaded.endTime" class="select-icon-close" type="close" size="20"
              @click.native.stop="closeFun(3)" color="#D9D9D9"></uni-icons>
          </view>
        </view>
        <view class="footer">
          <button plain type="primary" @click="confirmFilter()">查询</button>
        </view>
      </view>
      <view class="goods-list">
        <view class="item" v-for="(item, index) in listsDatas" style="margin-bottom: 10px">
          <unloading-waybill :itemList="item" @loadedFinish="loadedFinishFun" :types="currentTabs"></unloading-waybill>
        </view>
        <uni-load-more :status="pageParams.isMore" />
      </view>
    </view>

    <more-search ref="moreSearchRef" :show="popShow" :list="stateList" :type="currentTab" @filterChange="sureClick"
      @closePop="popShow=false"></more-search>
    <more-search ref="moreSearchRef" :show="popShows" :list="stateList" :type="currentTab" @filterChange="sureClick"
      @closePop="popShows=false"></more-search>
    <!-- 挂起 -->
    <uni-popup ref="SuspendDialog">
      <view class="pop violation-pop">
        <view class="phxx-itemss">
          <view class="header">
            <view class="title">挂起</view>
          </view>
          <view class="top hold-on">
            <view class="infor-box">
              <uni-forms-item class="label" label="运单状态" name="statusName">
                {{ statusNames[holdData.status] }}
              </uni-forms-item>
              <uni-forms-item class="label" label="挂起原因" required name="remark">
                <textarea v-model="confirmSuspendParam.remark" placeholder="请输入挂起原因" maxlength="100"></textarea>
              </uni-forms-item>
            </view>
          </view>
          <view class="btn">
            <button class="mini-btn" @click.stop="close()" type="primary" plain="true" size="mini">
              取消
            </button>
            <button class="mini-btn" @click.stop="SuspendConfirm(holdData)" type="primary" plain="true" size="mini">
              确认
            </button>
          </view>
        </view>
      </view>
    </uni-popup>
    <!-- 挂起 -->
    <uni-popup ref="RecoveryDialog">
      <view class="pop violation-pop">
        <view class="phxx-itemss">
          <view class="header">
            <view class="title">挂起恢复</view>
          </view>
          <view class="top hold-ons">
            <view class="infor-box">
              <uni-forms-item class="label" label="运单状态" name="statusName">
                <lable>{{ statusNames[statusShow] }}</lable>
              </uni-forms-item>
              <uni-forms-item class="label" label="挂起原因" name="remark">
                <lable>{{ confirmSuspendParam.remark }}</lable>
              </uni-forms-item>
            </view>
          </view>
          <view class="btn">
            <button class="mini-btn" @click.stop="close1()" type="primary" plain="true" size="mini">
              取消
            </button>
            <button class="mini-btn" @click.stop="RecoveryConfirm()" type="primary" plain="true" size="mini">
              确认
            </button>
          </view>
        </view>
      </view>
    </uni-popup>
    <u-modal :show="showConfir" @confirm="loadedFun" confirmText="我知道了">
      <view class="confir-box">
        <view class="images-box">
          <image src="@/static/images/ok.png" xlass="img"></image>
        </view>
        <view>确认装车成功</view>
      </view>
    </u-modal>
    <uni-popup ref="proDialog" type="bottom">
      <view style="background-color: #fff;">
        <view class="header">选择煤种</view>
        <scroll-view class="scroll-view" scroll-y="true">
          <view class="scroll-main" :style="{ height: type=='采购' ?' 460rpx' : '330rpx' }">
            <view :key="index" class="scroll-view-item" v-for="(item, index) in productList"
              @click="proClickItem(item,index)" :class="{ 'active-item': item.checked }">
              <view>{{ item.text }}</view>
              <view class="checked-icon" v-if="item.checked">√</view>
            </view>
          </view>
          <view class="scroll-footer">
            <button class="cancel" plain type="default" @click="cancleStatus">
              取消
            </button>
            <button plain type="primary" @click="confirmStatus">
              确定
            </button>
          </view>
        </scroll-view>
      </view>

    </uni-popup>
    <examine-form :show="isShowPop" :parentId="wayBillId" :cusId="customerId" :auditDataObj="auditDataObj" @closePop="closePop" :showOneyear="showOneyear"
      @examineCancel="examineCancel" @examinePass="examinePass"></examine-form>
    <cancel-confirm :popId="popId" :show="isShowCancelPop" @cancel="cancelForm" @success="successForm"></cancel-confirm>
    <view v-if="userType !== 1 && userType !== 2 && currentTabs === 0" class="countBox" @click="confirmFilter()">
      {{countdown}}s刷新/立即刷新</view>
    <!-- <custom-tabbar class="tabbar-box" :list="tabbarLists"></custom-tabbar> -->
    <view class="tabbar-box">
      <view v-for="(item,index) in tabbarLists" :key="index" class="my-tabbar"
        v-if="item.pagePath == '/pages/plans/index' ? (hasMenuPer && showPlanMenu) : !item.hidden">
        <view hover-class="none" class="weui-flex__item menu-item" @click="goToTab(item.pagePath)"
          :style="item.active? 'color: '+(item.selectedColor? item.selectedColor : selectedColor) : ''">
          <image :src="item.selectedIconPath" v-if="item.active" class="img"></image>
          <image :src="item.iconPath" v-if="!item.active" class="img"></image>
          <text class='tabbar_text'>{{item.text}}</text>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
  import config from '@/config';
  import cancelConfirm from "../common/cancelConfirm/cancelConfirm.vue"
  import { getBasisDeploy, getPurModel } from "@/api/system/user.js"
  import { cancelWaybill, confirmWaybill } from "@/api/waybill.js"
  import { getOrderLists, getSaleWaybillPage, editSaleWaybill, getLoadingDatas, productLists,getPlanFromWhere } from '@/api/tranplan.js';
  import {
    getAccessToken,
    getTenantId,
    getOpenId,
    getDriverId,
    getAccountIdentity
  } from '@/utils/auth';
  import { dictTansParams } from '@/utils/common.js';
  import {
    getDictDatas,
    getCoalLists,
    confirmReceipt,
    getTenantConfig,
    confirmSuspendFun,
    getSuspendInfoFun,
    confirmRecoveryFun
  } from '@/api/me.js';
  import { getInfo } from '@/api/login';
  import { toast, getButtonShow } from '@/utils/common.js';
  export default {
    data() {
      return {
        showOneyear: false,
        hasPermConfirm: false,
        showPlanMenu: false,
        hasPermCancel: false,
        timerFlag: '',
        popId: undefined,
        isShowCancelPop: false,
        orgNameShow: false,
        showConfir: false,
        countdown: 10,
        userType: getAccountIdentity(),
        paramDatas: {
          "pageNo": 1,
          "pageSize": 10,
          "status": 0,
          "userId": getDriverId(),
        },
        paramunLoaded: {
          carBrand: undefined,
          proId: undefined,
        },
        paramLoaded: {
          carBrand: undefined,
          startTime: undefined,
          endTime: undefined,
        },
        productText: undefined,
        choosePro: false,
        productList: [],
        productListAll: [],
        orderSuspend: false,
        tabbarLists: [
          {
            "pagePath": "/pages/index",
            "hidden": (getAccountIdentity() === 1 || getAccountIdentity() === 2) ? false : true,
            "active": false,
            "selectedColor": '#409EFE',
            "iconPath": require("static/images/tabbar/index.png"),
            "selectedIconPath": require("static/images/tabbar/index_.png"),
            "text": "首页"
          },
          {
            "pagePath": "/pages/devices/index",
            "hidden": (getAccountIdentity() === 1 || getAccountIdentity() === 2) ? true : false,
            "active": false,
            "selectedColor": '#409EFE',
            "iconPath": require("static/images/tabbar/device.png"),
            "selectedIconPath": require("static/images/tabbar/device_.png"),
            "text": "设备选择"
          },

          {
            "pagePath": "/pages/indexs",
            "hidden": (getAccountIdentity() === 1 || getAccountIdentity() === 2) ? false : true,
            "active": false,
            "selectedColor": '#409EFE',
            "iconPath": require("static/images/tabbar/home.png"),
            "selectedIconPath": require("static/images/tabbar/home_.png"),
            "text": "排号"
          },
          {
            "pagePath": "/pages/plans/index",
            "hidden": false,
            "active": false,
            "selectedColor": '#409EFE',
            "iconPath": require("static/images/tabbar/plan.png"),
            "selectedIconPath": require("static/images/tabbar/plan_.png"),
            "text": "计划"
          },
          {
            "pagePath": "/pages/waybill/index",
            "hidden": false,
            "active": true,
            "selectedColor": '#409EFE',
            "iconPath": require("static/images/tabbar/work.png"),
            "selectedIconPath": require("static/images/tabbar/work_.png"),
            "text": "运单"
          },
          {
            "pagePath": "/pages/mine/index",
            "hidden": false,
            "active": false,
            "selectedColor": '#409EFE',
            "iconPath": require("static/images/tabbar/mine.png"),
            "selectedIconPath": require("static/images/tabbar/mine_.png"),
            "text": "我的"
          }
        ],

        currentTabs: 0,
        statusNames: {
          0: '待供应商审核',
          1: '待采购方审核',
          2: '待入场',
          3: '待称毛',
          4: '待确认',
          5: '待录皮',
          6: '待出厂',
          7: '已完成',
          8: '已作废',
          9: '已终止',
          10: '挂起'
        },
        goodsData: [],
        holdData: {},
        popShow: false,
        popShows: false,
        coaltypeDatas: [],
        stateList: [],
        dataLists: [],
        titleLists: [],
        titleListsType: [
          '待装车', '已装车'
        ],
        isStart: false,
        isEnd: false,
        currentTab: '',
        hasMenuPer: true,
        queryParam: {
          carBrand: undefined,
          carCard: undefined,
          enterId: getTenantId(),
          proName: undefined,
          waybillStatus: undefined,
          userId: undefined,
          current: 1,
          pageSize: 10
        },
        saleQueryParam: {
          pageNo: 1,
          pageSize: 10,
          vehicleNo: undefined,
          coalSubtypeName: undefined,
          waybillStatus: undefined,
          smallProgramType: 2
        },
        pageParams: {
          isMore: 'more'
        },
        confirmReceiptParam: {
          orderId: undefined,
          userId: undefined
        },
        confirmSuspendParam: {
          id: undefined,
          remark: '',
          waybillType: 1
        },
        getSuspendInfoParam: {
          id: undefined,
          waybillType: 1
        },
        orderId: undefined,
        statusShow: '',
        isShowPop: false,
        wayBillId: undefined,
        customerId: undefined,
        waybillno: undefined,
        confirmAudit: false,
        confirmCancel: false,
        listsDatas: [],
        lastCheckIds: [],
        auditDataObj: {}
      };
    },
    computed: {
      filterIcon() {
        return config.baseImgUrl + '/more-fliter.png';
      }
    },
    components: {
      cancelConfirm
    },
    methods: {
      goToTab(url) {
        wx.switchTab({
          url: url  // 需要跳转的 tab 页路径
        })
      },
      startCountdown(type) {
        if (type === 1) {
          if (this.timerFlag) {
            clearInterval(this.timerFlag);
          }
          return
        }
        if (this.timerFlag) {
          clearInterval(this.timerFlag);
        }
        // 重置倒计时 
        this.countdown = 10

        // 设置定时器，每秒更新一次
        const timer = setInterval(() => {
          // 倒计时减1 
          this.countdown = this.countdown - 1

          // 如果倒计时结束
          if (this.countdown <= 0) {
            clearInterval(timer); // 清除当前定时器
            this.timerFlag = null
            this.startCountdown(0);
            this.getLoadingLists({ ...this.paramDatas, ...this.paramunLoaded });
          }
        }, 1000);
        // 存储定时器ID，方便后续清除
        this.timerFlag = timer
      },
      closeFun(type) {
        if (type === 1) {
          this.productText = ''
          this.paramunLoaded.proId = undefined
          this.getProductsLists()
        } else if (type === 2) {
          this.paramLoaded.startTime = undefined
        } else {
          this.paramLoaded.endTime = undefined
        }
      },
      async getProductsLists() {
        this.productList = []
        const res = await productLists()
        if (res.code == 0) {
          const proDatas = res.data
          this.productList = proDatas.map(item => {
            return {
              text: item.proName,
              id: item.id,
              checked: false
            }
          })
        }
      },
      loadedFun() {
        this.showConfir = false
        this.getLoadingLists(this.paramDatas)
      },
      loadedFinishFun() {
        this.showConfir = true
      },
      showEndTime() {
        this.isEnd = true
      },
      showStartTime() {
        this.isStart = true
      },
      onConfirm(value, type) {
        this.paramLoaded[type] = value.result
        this.isStart = false
        this.isEnd = false
      },
      onCancel() {
        this.isStart = false
        this.isEnd = false
      },
      confirmFilter() {
        this.paramDatas.pageNo = 1
        if (this.currentTabs === 0) {
          let param = {
            proId: undefined,
            carBrand: this.paramunLoaded.carBrand
          }
          this.paramDatas.status = 0
          this.getLoadingLists({ ...this.paramDatas, ...this.paramunLoaded });
        } else {
          if (new Date(this.paramLoaded.endTime) < new Date(this.paramLoaded.startTime)) {
            toast('结束时间不能早于开始时间');
            return
          }
          this.paramDatas.status = 1
          this.getLoadingLists({ ...this.paramDatas, ...this.paramLoaded });
        }
      },
      proClickItem(item, index) {
        this.lastCheckIds.push(index)
        this.productList[index].checked = !this.productList[index].checked
      },
      cancleStatus() {
        if (this.lastCheckIds.length > 0) {
          this.lastCheckIds.forEach(item => {
            this.productList[item].checked = !this.productList[item].checked
          })
        }
        this.$refs.proDialog.close();
      },
      confirmStatus() {
        this.lastCheckIds = []
        let results = this.productList.filter(item => item.checked)
        this.productText = results.map(item => item.text).join(",")
        this.paramunLoaded.proId = results.map(item => item.id).join(",")
        this.$refs.proDialog.close();
      },
      chooseProFun() {
        if (this.productList.length === 0) {
          toast('产品列表暂时为空');
          return;
        }
        this.$refs.proDialog.open();
      },
      async getbuttonAuth() {
        //调用公共方法

        let orderAppSuspend = 'order:Suspend';
        this.hasPermConfirm = await getButtonShow('purWaybill:confirm')
        this.hasPermCancel = await getButtonShow('purWaybill:cancel')
        this.orderSuspend = await getButtonShow(orderAppSuspend);
        this.confirmAudit = await getButtonShow('enterprise-waybill:confirmAudit')
        this.confirmCancel = await getButtonShow('enterprise-waybill:cancel')
      },
      closePop() {
        this.isShowPop = false
      },
      examineCancel() {
        this.closePop()
        this.goodsData = []
        this.pageParams.isMore = 'more'
        this.saleQueryParam.pageNo = 1;
        this.getSaleWaybillPage()
        toast('审核作废成功');
      },
      examinePass() {
        this.closePop()
        this.goodsData = []
        this.pageParams.isMore = 'more'
        this.saleQueryParam.pageNo = 1;
        this.getSaleWaybillPage()
        toast('审核通过成功');
      },
      async cancelWaybill(data) {
        const res = await editSaleWaybill(data)
        if (res.code === 0) {
          this.goodsData = []
          this.pageParams.isMore = 'more'
          this.saleQueryParam.pageNo = 1;
          this.getSaleWaybillPage()
          toast('取消运单成功');
        } else {
          toast(res.msg);
        }
      },
      async confirmExamine(item) {
        this.waybillno = item.waybillNo
        this.wayBillId = item.id
        this.customerId = item.customerId
        const resPlan = await getPlanFromWhere(item.planNo)
        if (resPlan.code == 200) {
          if (resPlan.data.whetherSalePlan) {
            this.auditDataObj = {
              addressData: [{'value': resPlan.data.addressId, 'text': resPlan.data.addressName}],
              proData: [{ 'value': resPlan.data.productId, 'text': resPlan.data.productName }],
              relId: resPlan.data.relId
            }
          }
        }
        this.isShowPop = true
      },
      showGuaqiDialog(data) {
        this.holdData = data;
        this.$refs.SuspendDialog.open();
        this.confirmSuspendParam.remark = '';
      },
      showCancelDialog(data) {
        this.popId = data.id
        this.isShowCancelPop = true
      },
      successForm() {
        this.queryParam.current = 1
        this.getDatas();
        this.isShowCancelPop = false
      },
      showGoodsDialog(data) {
        this.holdData = data;
        this.$refs.SuspendDialog.open();
        this.confirmSuspendParam.remark = '';
      },
      async showHuifuDialog(data) {
        this.$refs.RecoveryDialog.open();
        this.getSuspendInfoParam.id = data.id;
        let res = await getSuspendInfoFun(this.getSuspendInfoParam);
        if (res.code == 0 && res.data != null) {
          this.confirmSuspendParam.remark = res.data.remark;
          this.statusShow = res.data.waybillStatus;
          this.confirmSuspendParam.id = res.data.orderId;
        }
      },
      async SuspendConfirm(item) {
        if (
          this.confirmSuspendParam.remark == '' ||
          this.confirmSuspendParam.remark == null
        ) {
          toast('请输入挂起原因');
          return false;
        }
        this.confirmSuspendParam.id = item.id;
        this.$refs.SuspendDialog.close();
        let res = await confirmSuspendFun(this.confirmSuspendParam);
        if (res.code == 0) {
          toast('挂起成功');
          this.getDatas();
        } else {
          toast(res.msg);
        }
      },
      async RecoveryConfirm() {
        if (
          this.confirmSuspendParam.remark == '' ||
          this.confirmSuspendParam.remark == null
        ) {
          toast('挂起原因为空');
          return false;
        }
        this.$refs.RecoveryDialog.close();
        let res = await confirmRecoveryFun(this.confirmSuspendParam);
        if (res.code == 0) {
          toast('挂起恢复成功');
          this.getDatas();
        } else {
          toast(res.msg);
        }
      },
      close() {
        this.$refs.SuspendDialog.close();
      },
      close1() {
        this.$refs.RecoveryDialog.close();
      },
      showPopClick() {
        this.popShow = true;
      },
      showPopClicks() {
        this.popShows = true;
      },
      sureClick(datas) {
        this.popShow = false;
        if (this.currentTab === '采购') {
          this.queryParam.current = 1;
          this.queryParam.carBrand = datas.carBrand;
          this.queryParam.waybillStatus = datas.waybillStatus;
          this.queryParam.carCard = datas.carCard;
          this.queryParam.proName = datas.proName;
          this.getDatas();
        }
        if (this.currentTab === '销售') {
          this.goodsData = []
          this.saleQueryParam = {
            pageNo: 1,
            pageSize: 10,
            vehicleNo: datas.carBrand,
            coalSubtypeName: datas.proName,
            waybillStatus: datas.waybillStatus,
            smallProgramType: 2
          }
          this.getSaleWaybillPage()
        }
        this.popShow = false
      },
      async showButton(item) {
        this.confirmReceiptParam.orderId = item.id;
        this.confirmReceiptParam.userId = getDriverId();
        let res = await confirmReceipt(this.confirmReceiptParam);
        if (res.code == 0) {
          uni.showToast({
            title: '确认收货成功',
            icon: 'success',
            success: () => {
              setTimeout(() => {
                this.getDatas();
              }, 1000);
            }
          });
        } else {
          uni.showToast({
            title: '收货失败',
            icon: 'failed'
          });
        }
      },
      changeCoaltype(e) {
        this.coaltypeDatas.forEach((item) => {
          if (item.value == e) this.queryParam.proName = item.text;
        });
      },
      async getCoalList() {
        let res = await getCoalLists(this.queryParam.enterId);
        if (res.code == 200) {
          this.coaltypeDatas = res.data.map((item) => {
            return {
              value: item.id,
              text: item.proName
            };
          });
        }
      },
      clickItemFun(tab) {
        this.currentTabs = tab
        this.paramDatas.pageNo = 1
        this.paramDatas.status = tab
        this.listsDatas = []
        this.getLoadingLists({ ...this.paramDatas })
        if (tab === 0) {
          this.startCountdown(0)
        } else {
          this.startCountdown(1)
        }
      },
      clickItem(tab) {
        this.currentTab = tab
        this.getDictLists()
        this.getbuttonAuth()
        this.goodsData = []
        this.resetQueryParam()
        this.$refs.moreSearchRef?.resetFilter()
        this.pageParams.isMore = 'more'
        if (this.currentTab === '销售') {
          this.saleQueryParam.pageNo = 1;
          this.getSaleWaybillPage()
        }
        if (this.currentTab === '采购') {
          this.queryParam.current = 1;
          this.getDatas()
        }
      },
      resetQueryParam() {
        this.queryParam.carBrand = undefined
        this.queryParam.carCard = undefined
        this.queryParam.proName = undefined
        this.queryParam.waybillStatus = undefined
        this.saleQueryParam.vehicleNo = undefined
        this.saleQueryParam.coalSubtypeName = undefined
        this.saleQueryParam.waybillStatus = undefined
      },
      async getDatas() {
        this.queryParam.userId = getDriverId();
        let res = await getOrderLists(this.queryParam);
        if (res.code == '200') {
          if (this.queryParam.current == 1) {
            this.goodsData = res.data.rows;
          } else {
            this.goodsData = [...this.goodsData, ...res.data.rows];
          }
          if (res.data.total == this.goodsData.length) {
            this.pageParams.isMore = 'noMore';
          } else {
            this.pageParams.isMore = 'more';
          }
        }
        //停止下拉刷新
        wx.hideNavigationBarLoading();
        //停止下拉刷新
        wx.stopPullDownRefresh();
      },
      searchMore() {
        this.$refs['searchPopup'].open();
      },
      searchData() {
        this.queryParam.current = 1;
        this.getDatas();
        this.$refs['searchPopup'].close();
      },
      goToSaleDetail(item) {
        uni.navigateTo({
          url: `/pages/waybill/saleDetails?id=${item.id}`
        });
      },
      goToLoadDetail(item) {
        uni.navigateTo({
          url: `/pages/waybill/loadDetails?id=${item.id}`
        });
      },
      goToLoadingDetail(item) {
        uni.navigateTo({
          url: `/pages/waybill/lodingDetails?id=${item.id}`
        });
      },
      goToDetail(item) {
        uni.navigateTo({
          url: `/pages/waybill/details?id=${item.id}`
        });
      },
      async getDictLists() {
        const datas = await getDictDatas();
        let res = [];
        if (this.currentTab === '销售') {
          res = await dictTansParams(datas.data, 'sale_waybill_status');
          console.log('sale_waybill_status', res)
        }
        if (this.currentTab === '采购') {
          res = await dictTansParams(datas.data, 'purchase_waybill_status');
        }
        this.stateList = res.map((item) => {
          return {
            value: item.value,
            text: item.text
          };
        });
      },
      async getTenantConfig() {
        let res = await getTenantConfig();
        if (res.code === 0) {
          this.titleLists = []
          const result = res.data.bizType || []
          this.pageParams.isMore = 'more'
          if (result.includes('2')) {
            this.titleLists.push('销售')
            this.currentTab = '销售'
            this.goodsData = []
            this.saleQueryParam.pageNo = 1;
            this.getSaleWaybillPage()
          }
          if (result.includes('1')) {
            this.titleLists.push('采购')
            if (!this.currentTab) {
              this.currentTab = '采购'
              this.goodsData = []
              this.queryParam.current = 1;
              this.getDatas();
            }
          }
        }
      },
      async getSaleWaybillPage() {
        let res = await getSaleWaybillPage(this.saleQueryParam);
        if (res.code === 0) {
          const result = res.data?.list || [];
          const total = res.data?.total || 0;
          this.goodsData = [...this.goodsData, ...result]
          if (total == this.goodsData.length) {
            this.pageParams.isMore = 'noMore';
          } else {
            this.pageParams.isMore = 'more';
          }
        }
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
      },
      async getLoadingLists(params) {
        if (params?.carBrand === '') {
          params['carBrand'] = undefined
        }
        let res = await getLoadingDatas(params);
        if (res.code == 100200008) {
          toast(res.msg);
          return
        }
        if (res.code === 0) {
          if (this.paramDatas.pageNo == 1) {
            this.listsDatas = []
          }
          const result = res.data?.list || [];
          const total = res.data?.total || 0;
          this.listsDatas = [...this.listsDatas, ...result]
          if (total == this.listsDatas.length) {
            this.pageParams.isMore = 'noMore';
          } else {
            this.pageParams.isMore = 'more';
          }
        }

      },
    },
    async onShow() {
      let purmodel = await getPurModel()
      if (purmodel.code == 0) {
        this.showPlanMenu = purmodel.data.purchaseBizMode == 1 ? true : false
      }
      let permissionsLists = [];
      let plists = await getInfo({
        enterId: getTenantId(),
        userId: getDriverId()
      });
      permissionsLists = plists?.data?.permissions || [];
      this.hasMenuPer = permissionsLists.some(
        (item) => item == 'plan:view'
      );
      let res = await getBasisDeploy(getTenantId())
      if (res.code == 200) {
        this.orgNameShow = res?.data?.isEnabledOrganization === 1 ? true : false
        if (res?.data?.percentageOfPerformance == null) {
          this.showOneyear = false
        } else {
          this.showOneyear = true
        }
      }
      this.popShow = false;
      this.resetQueryParam()
      this.$refs.moreSearchRef?.resetFilter()
      if (this.userType === 1 || this.userType === 2) {
        this.getbuttonAuth();
        this.getDictLists();
        this.getCoalList();
        this.getTenantConfig();
      } else {
        this.startCountdown(0)
        this.getProductsLists()
        this.getLoadingLists(this.paramDatas);
      }
    },
    onReachBottom() {
      if (getAccountIdentity() === 1 || getAccountIdentity() === 2) {
        if (this.pageParams.isMore === 'more') {
          if (this.currentTab === '销售') {
            this.saleQueryParam.pageNo++;
            this.getSaleWaybillPage()
          }
          if (this.currentTab === '采购') {
            this.queryParam.current++;
            this.getDatas()
          }
        }
      } else {
        this.paramDatas.pageNo++
        if (this.currentTabs === 0) {
          this.paramDatas.status = 0
          this.getLoadingLists({ ...this.paramDatas, ...this.paramunLoaded });
        } else {
          this.paramDatas.status = 1
          this.getLoadingLists({ ...this.paramDatas, ...this.paramLoaded });
        }
      }
    },
    onPullDownRefresh() {
      if (getAccountIdentity() === 1 || getAccountIdentity() === 2) {
        this.goodsData = []
        this.pageParams.isMore = 'more'
        this.getbuttonAuth();
        if (this.currentTab === '销售') {
          this.saleQueryParam.pageNo = 1;
          this.getSaleWaybillPage()
        }
        if (this.currentTab === '采购') {
          this.queryParam.current = 1;
          this.getDatas()
        }
      } else {
        this.paramDatas.pageNo = 1
        this.getProductsLists()
        this.getLoadingLists(this.paramDatas);
      }
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    },
    onUnload() {
      if (this.timerFlag) {
        clearInterval(this.timerFlag);
      }
    },
    onHide() {
      if (this.timerFlag) {
        clearInterval(this.timerFlag);
      }
    },
  };
</script>

<style lang="scss" scoped>
  .countBox {
    color: #409eff;
    position: fixed;
    bottom: 142rpx;
    height: 68rpx;
    background-color: #fff;
    line-height: 68rpx;
    width: 100%;
    text-align: center;
    cursor: pointer;
  }

  .select-icon-close {
    position: absolute;
    right: 15px;
    top: 11px;
    background: #fff;
    z-index: 9;
    height: 55rpx;
  }

  .header {
    height: 46px;
    line-height: 46px;
    font-size: 16px;
    font-weight: bold;
    text-align: center;
    border-bottom: 1px solid #E6E6E6;
  }

  .scroll-view {
    padding: 17.78rpx 35.56rpx 0 35.56rpx;
    width: 100vw;
    background-color: #fff;
    bottom: 0;
    position: relative;
    font-size: 16px;

    .scroll-view-item+.scroll-view-item {
      margin-top: 10.67rpx;
    }

    .search-box {
      margin: 0 0 23.11rpx 5.33rpx;

      text {
        width: 130rpx;
      }
    }

    .scroll-view-item {
      display: flex;
      justify-content: space-between;
      padding: 14.22rpx 17.78rpx;
      border-radius: 7.11rpx;
      border-bottom: 1px solid #E6E6E6;

      .checked-icon {
        font-size: 24.89rpx;
        font-weight: bold;
      }
    }

    .scroll-main {
      overflow-y: auto;
    }

    .scroll-footer {
      display: flex;
      justify-content: space-between;
      padding: 0 0 10px 0;

      button {
        width: 49.5%;
        font-size: 15px !important;
      }
    }
  }

  .search-boxs {
    margin: 10px;
    background: #fff;
    padding: 10px;
    position: relative;

    .items-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .footer {
      margin-top: 10px;
    }

    .items.full {
      width: 100%;
    }

    .items {
      width: 49.5%;
      height: 40px;
      font-size: 17px;
      margin-bottom: 10px;

      .uni-form-item {
        position: relative;
        width: 100%;
        font-size: 17px !important;
      }

      .space {
        width: 5%;
      }

      .select-label {
        height: 40px;
        line-height: 40px;
        display: inline-block;
        color: #999;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .select-wrap,
      input {
        border: 1px solid #D9D9D9;
        border-radius: 4px;
        height: 40px;
        line-height: 40px;
        padding: 0 8px;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
    }

    .items:first-child {
      margin-right: 1%;
    }
  }

  .container {
    .goods-list {
      padding: 20rpx 20rpx 112rpx 20rpx;
    }

    .search-box {
      display: flex;
      align-items: center;
      color: #333333;
      margin-right: 10px;

      >text {
        position: relative;
        top: -1px;
      }

      >image {
        width: 20px;
        height: 20px;
      }
    }

    .searchPopup {
      position: absolute;
      right: 0;

      .up-searcbox {
        background: #fff;
        width: 410rpx;
        position: absolute;
        right: -195px;
        height: 100vh;
        padding: 10px;
        top: -320px;

        .search-header {
          .items {
            margin-bottom: 10px;

            input {
              border: 1px solid #ccc;
              border-radius: 3px;
              height: 30px;
              margin-top: 5px;
              padding: 0 2px;
            }

            .net-selct-box {
              width: 77%;
            }
          }
        }

        .search-footer {
          bottom: 50%;
          position: absolute;
          display: flex;
          align-content: center;
          flex-flow: nowrap;

          button {
            float: left;
            font-size: 21.33rpx !important;
            border: 1px solid #409eff !important;
          }

          button:nth-child(2) {
            margin-left: 10px;
          }
        }
      }
    }
  }

  .header-wrap {
    height: 36px;
    font-size: 15px;
    background: #fff;

    .tab-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid #E6E6E6;
    }
  }

  .tags {
    display: flex;
    height: 36px;
    padding: 0 10px;
    line-height: 36px;
    text-align: center;
    width: 100%;

    .tag-view+.tag-view {
      margin-left: 20px;
    }

    .tag-view {
      width: 30px;
      cursor: pointer;
      color: #333333;
      padding-bottom: 20px;
    }

    .tag-view.active {
      color: #409eff;
      border-bottom: 2px solid #409eff;
    }
  }
</style>